package com.cn.system.controller;

import com.cn.common.result.Result;
import com.cn.common.result.ResultCodeEnum;
import com.cn.common.utils.JwtHelper;
import com.cn.common.utils.MD5;
import com.cn.model.system.SysUser;
import com.cn.model.vo.LoginVo;
import com.cn.system.execption.GuiguException;
import com.cn.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 后台登录登出
 */
@Api
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {
    @Autowired
    private SysUserService sysUserService;

    /**
     * 登录
     *
     * @return
     */
    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo) {
        //根据username查询数据
        SysUser sysUser=sysUserService.getByUsername(loginVo.getUsername());
        //是否为空，判断密码是否一致
        if (null==sysUser){
            throw new GuiguException(ResultCodeEnum.ACCOUNT_ERROR);
        }
        if (!MD5.encrypt(loginVo.getPassword()).equals(sysUser.getPassword())){
            throw new GuiguException(ResultCodeEnum.PASSWORD_ERROR);
        }
        //判断用户是否可用
        if (sysUser.getStatus().intValue()==0){
            throw new GuiguException(ResultCodeEnum.ACCOUNT_STOP);
        }
        HashMap<String, Object> map = new HashMap<>();
//        map.put("token", "admin");
        map.put("token", JwtHelper.createToken(sysUser.getId(), sysUser.getUsername()));
        return Result.ok(map);
    }
    /**
     * 获取用户信息
     * @return
     */
    @ApiOperation(value = "获取用户信息")
    @GetMapping("/info")
    public Result info(HttpServletRequest request) {
        //获取token字符串  从token字符串获取用户名称 id
        String username = JwtHelper.getUsername(request.getHeader("token"));
        //根据用户名获取用户信息（基本信息 菜单权限 按钮权限数据）
        Map<String,Object> map=sysUserService.getUserInfo(username);
        return Result.ok(map);
    }
    /**
     * 退出
     * @return
     */
    @PostMapping("/logout")
    public Result logout(){
        return Result.ok();
    }
}
